<template>
  <el-dialog
    :title="title + '租赁物设备信息'"
    :visible="dialogVisible"
    width="50%"
    append-to-body
    :before-close="handleClose"
    :close-on-click-modal="false"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-col :span="24">
        <el-form-item label="所属厂商">
          <span style="width: 240px;">{{ $store.state.user.company?.companyName }}</span>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          label="设备名称"
          prop="equipmentName"
        >
          <el-input
            v-model="form.equipmentName"
            placeholder="请输入设备名称"
          />
        </el-form-item>
      </el-col>
      <el-col :span="9">
        <el-form-item
          label="设备分类"
          prop="equipmentType"
        >
          <el-select
            v-model="form.equipmentType"
            placeholder="请选择设备分类"
            clearable
          >
            <el-option
              v-for="item in deviceTypeList"
              :key="item.equipmentType"
              :label="item.equipmentType"
              :value="item.equipmentType"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="3">
        <el-button
          size="mini"
          type="primary"
          @click="handleType"
          style="margin-left: 20px;margin-top: 3px;"
        >
          类别管理
        </el-button>
      </el-col>
      <el-col :span="12">
        <el-form-item
          label="单位"
          prop="unit"
        >
          <el-input
            v-model="form.unit"
            placeholder="请输入单位"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          label="规格型号"
          prop="equipmentModel"
        >
          <el-input
            v-model="form.equipmentModel"
            placeholder="请输入规格型号"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item
          label="指导价"
          prop="price"
        >
          <el-input
            v-model.number="form.price"
            type="number"
            min="0"
            placeholder="请输入指导价"
            style="width: 100%;"
            @blur="handlePriceBlur($event, 'price')"
          >
            <template slot="append">万元</template>
          </el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item
          label="配置信息"
          prop="configInfo"
        >
          <el-input
            v-model="form.configInfo"
            type="textarea"
            placeholder="请输入配置信息"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <div
          class="up_sy_logo_div"
          style="margin-left: 40px;"
        >
          <!--支持点击查看大图-->
          <el-image
            v-if="ruleForm.hrefn"
            style="width: 250px;height :175px;"
            :src="ruleForm.hrefn"
            :preview-src-list="ruleForm.hrefn ? [ruleForm.hrefn] : []"
          ></el-image>
        </div>
        <el-upload
          :accept="pic_accept"
          :action="uploadFileUrl + '/file/saveFile'"
          :before-upload="beforeAvatarUpload"
          :on-success="handleLicenseSuccess"
          :data="{fileRemark: '', fileuserInfo: ''}"
          :show-file-list="false"
        >
          <el-button
            style="margin: 10px 0 0 90px;"
            size="small"
            type="primary"
          >上传设备图片</el-button>
        </el-upload>
      </el-col>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button
        type="primary"
        @click="submitForm"
      >确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <el-dialog
      title="设备分类"
      :visible.sync="deviceTypeOpen"
      v-loading="dialogLoading"
      width="30%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form
        ref="deviceTypeForm"
        :model="deviceTypeForm"
        label-width="80px"
      >
        <el-col :span="12">
          <el-form-item
            label="分类名称"
            prop="equipmentType"
          >
            <el-input
              v-model="deviceTypeForm.equipmentType"
              placeholder="请输入分类名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-button
            size="mini"
            type="primary"
            @click="handleAddType"
            style="margin-left: 20px;margin-top: 3px;"
          >
            新增
          </el-button>
        </el-col>
        <el-table
          v-loading="deviceTypeLoading"
          :data="deviceTypeList"
          height="500px"
        >
          <el-table-column
            label="类别名称"
            align="center"
            prop="equipmentType"
            :show-overflow-tooltip="true"
            min-width="150"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteType(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { addEquimpent, updateEquimpent, listEquimpentType, addEquimpentType, delEquimpentType } from '@/api/deviceCatalog'
import { queryFiles } from '@/api/agent/index'
export default {
  data() {
    var validatePositiveNumberWithDecimal = (rule, value, callback) => {
      if (value === null || value === '' || isNaN(value)) {
        // 如果输入为空、null或无法转换为数字，则视为有效（因为是非必填项）
        callback();
      } else if (value <= 0) {
        // 如果输入的数字小于等于0，则给出错误提示
        callback(new Error('请输入大于0的数字'));
      } else {
        // 检查小数点后的位数
        const decimalPart = value.toString().split('.')[1];
        if (decimalPart && decimalPart.length > 6) {
          // 如果小数点后位数超过6位，则给出错误提示
          callback(new Error('小数点后最多6位'));
        } else {
          // 输入有效
          callback();
        }
      }
    };
    return {
      dialogVisible: false,
      title: '新增',
      uploadFileUrl: process.env.VUE_APP_BASE_API,

      dialogLoading: false,
      form: {},
      rules: {
        equipmentName: [
          { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        equipmentType: [
          { required: true, message: '设备分类不能为空', trigger: 'change' }
        ],
        unit: [
          { required: true, message: '单位不能为空', trigger: 'blur' }
        ],
        equipmentModel: [
          { required: true, message: '规格型号不能为空', trigger: 'blur' }
        ],
        price: [
          { validator: validatePositiveNumberWithDecimal, trigger: 'blur' },
        ],
      },
      deviceTypeLoading: false,
      deviceTypeOpen: false,
      deviceTypeForm: {},
      deviceTypeList: [],
      ruleForm: {
        hrefn: require("@/assets/images/space.png")
      },
      pic_accept: ".jpg,.png,.jpeg,.bmp",
      pic_maxsize: 10,//单位MB
    }
  },
  methods: {
    sync(row) {
      this.dialogVisible = true
      if (row) {
        this.title = '编辑'
        this.reset()
        this.form.id = row.id
        this.form.equipmentName = row.equipmentName
        this.form.equipmentType = row.equipmentType
        this.form.unit = row.unit
        this.form.equipmentModel = row.equipmentModel
        this.form.price = Number((row.price / 10000).toFixed(4))
        this.form.configInfo = row.configInfo
        this.form.fileId = row.fileId
        if (this.form.fileId.length > 0) {
          queryFiles({
            fileId: this.form.fileId,
            modelKey: 'original'
          }).then(res => {
            const blob = new Blob([res], { type: "image/jpeg" })
            const fileUrl = window.URL.createObjectURL(blob);
            this.ruleForm.hrefn = fileUrl
          })
        }
      } else {
        this.title = '新增'
        this.reset()
        this.ruleForm.hrefn = require("@/assets/images/space.png")
        this.getDeviceTypeList()
      }
    },
    handlePriceBlur(e, type) {
      this.form[type] = e.target.valueAsNumber.toFixed(4)
    },
    // 取消按钮
    cancel() {
      this.dialogVisible = false
      this.reset()
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        equipmentName: undefined,
        equipmentType: undefined,
        unit: undefined,
        equipmentModel: undefined,
        price: undefined,
        configInfo: undefined,
        fileId: undefined
      }
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          let params = {
            ...this.form,
            price: Number((this.form.price * 10000).toFixed(2)),
            company: this.$store.state.user.company.companyName
          }
          if (this.form.id != undefined) {
            updateEquimpent(params).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.dialogVisible = false
              this.$emit('clickChange')
            })
          } else {
            addEquimpent(params).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.dialogVisible = false
              this.$emit('clickChange')
            })
          }
        }
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    handleLicenseSuccess(response, file) {
      this.ruleForm.hrefn = URL.createObjectURL(file.raw);
      this.form.fileId = response.data.fileUuid
    },
    beforeAvatarUpload(file) {
      if (!this.checkFile(file)) {
        return false;
      }
    },
    checkFile(file) {
      //  判断图片类型
      if (this.pic_accept) {
        let picTypeArr = this.pic_accept.split(',');
        let isImage = picTypeArr.some(item => file.type === 'image/' + item.replace(/^\./, ''));
        if (!isImage) {
          this.$modal.msgError('上传图片只能是 （' + this.pic_accept + '） 格式!');
          return false;
        }
      }
      //  判断图片大小
      if (this.pic_maxsize > 0) {
        let isLtNumM = file.size / 1024 / 1024 < this.pic_maxsize;
        if (!isLtNumM) {
          this.$modal.msgError('上传图片大小不能超过 ' + this.pic_maxsize + 'MB!');
          return false;
        }
      }
      return true;
    },
    // 获取设备分类下拉框选项
    getDeviceTypeList() {
      this.dialogLoading = true
      listEquimpentType().then(response => {
        this.deviceTypeList = response.rows;
        this.dialogLoading = false
      })
    },
    // 类别管理
    handleType() {
      this.deviceTypeOpen = true
      this.getDeviceTypeList()
    },

    handleAddType() {
      if(this.deviceTypeForm.equipmentType){
         let params = {
          ...this.deviceTypeForm,
          company: this.$store.state.user.company.companyName
        }
        addEquimpentType(params).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.deviceTypeForm.equipmentType = undefined
          this.getDeviceTypeList()
        })
      }else{
        this.$modal.msgError('请输入分类名称');
      }
    },

    handleDeleteType(row) {
      this.$modal.confirm('是否确认删除该数据项？').then(function () {
        return delEquimpentType(row.id)
      }).then(() => {
        this.getDeviceTypeList()
        this.$modal.msgSuccess('删除成功')
        if (row.equipmentType === this.form.equipmentType) {
          this.form.equipmentType = ''
        }
      }).catch(() => { })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
